// Package ordererInfo
// @Description: 排序服务信息
package ordererInfo

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

type OrdererOrgInfo struct {
	Name      string   // like "OrdererOrg"
	AdminUser string   // like "Admin"
	Endpoint  []string // like "orderer.example.com"
	//OrdererClientContext *contextAPI.ClientProvider // oderer节点资源客户端 用于创建通道
}

// New 新建Orderer实例
func New(name string, adminUser string, endpoint []string) *OrdererOrgInfo {
	oderer := OrdererOrgInfo{
		Name:      name,
		AdminUser: adminUser,
		Endpoint:  endpoint,
	}
	return &oderer
}

// CreatResmgmtClient 创建orderer组织管理员资源客户端--用于创建通道
func (o *OrdererOrgInfo) CreatResmgmtClient(fabSDK *fabsdk.FabricSDK) (mgmtClient *resmgmt.Client, err error) {
	// 创建上下文
	ordererClientContext := fabSDK.Context(fabsdk.WithUser(o.AdminUser), fabsdk.WithOrg(o.Name))
	// 创建客户端
	mgmtClient, err = resmgmt.New(ordererClientContext)
	if err != nil {
		return nil, fmt.Errorf("CreatResmgmt err:%v", err)
	}
	return mgmtClient, nil
}

//
//  CreateChannel
//  @Description:
//  @receiver o
//  @param signIDs
//  @param channelID
//  @param channelConfigPath 为xxchannel.tx文件的路径
//  @return error
//
func (o *OrdererOrgInfo) CreateChannel(fabSDK *fabsdk.FabricSDK, signIDs []msp.SigningIdentity, channelID string, channelConfigPath string) error {
	// 获取orderer组织管理员资源客户端
	mgmtClient, err := o.CreatResmgmtClient(fabSDK)
	if err != nil {
		return fmt.Errorf("CreateChannel err:%v", err)
	}
	// orderer组织管理员资源客户端 为xxchannel.tx创建通道
	req := resmgmt.SaveChannelRequest{
		ChannelID:         channelID,
		ChannelConfigPath: channelConfigPath,
		SigningIdentities: signIDs,
	}
	if _, err := mgmtClient.SaveChannel(req, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(o.Endpoint[0])); err != nil {
		return fmt.Errorf("CreateChannel: %v", err)
	}
	//fmt.Println(">>>> 使用每个org的管理员身份更新锚节点配置...")
	////do the same get ch client and create channel for each anchor peer as well (first for Org1MSP)
	//for i, org := range info.Orgs {
	//	req = resmgmt.SaveChannelRequest{
	//		ChannelID: info.ChannelID,
	//		ChannelConfigPath: org.OrgAnchorFile,
	//		SigningIdentities: []msp.SigningIdentity{signIDs[i]},
	//	}
	//
	//	if _, err = org.OrgResMgmt.SaveChannel(req, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint("orderer.example.com")); err != nil {
	//		return fmt.Errorf("SaveChannel for anchor org %s error: %v", org.OrgName, err)
	//	}
	//}
	//fmt.Println(">>>> 使用每个org的管理员身份更新锚节点配置完成")
	return nil
}
